package com.aiyige.utils;

import android.text.TextUtils;
import android.text.format.Time;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;

public class TimeUtils {

    public static String formatTalkTime(long when) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(when);
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        if (isToday(when)) {
            return format.format(calendar.getTime());
        } else if (isYesterday(when)) {
            return "昨天" + format.format(calendar.getTime());
        } else {
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return format.format(calendar.getTime());
        }
    }

    public static String formatDateTime(long when) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(when);
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");

        if (isToday(when)) {
            return "今天" + format.format(calendar.getTime());
        } else if (isYesterday(when)) {
            return "昨天" + format.format(calendar.getTime());
        } else {
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return format.format(calendar.getTime());
        }
    }

    public static String formatDateTimeMMDD(long when) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(when);
        SimpleDateFormat format = new SimpleDateFormat("MM-dd");

        if (isToday(when)) {
            return "今天";
        } else if (isYesterday(when)) {
            return "昨天";
        } else {
            format = new SimpleDateFormat("MM-dd");
            return format.format(calendar.getTime());
        }
    }

    public static boolean isToday(long when) {
        Time time = new Time();
        time.set(when);

        int thenYear = time.year;
        int thenMonth = time.month;
        int thenMonthDay = time.monthDay;

        time.set(System.currentTimeMillis());
        return (thenYear == time.year)
                && (thenMonth == time.month)
                && (thenMonthDay == time.monthDay);
    }

    public static boolean isYesterday(long when) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);

        int thenYear = calendar.get(Calendar.YEAR);
        int thenMonth = calendar.get(Calendar.MONTH);
        int thenMonthDay = calendar.get(Calendar.DAY_OF_MONTH);

        calendar.setTimeInMillis(when);
        return (thenYear == calendar.get(Calendar.YEAR))
                && (thenMonth == calendar.get(Calendar.MONTH))
                && (thenMonthDay == calendar.get(Calendar.DAY_OF_MONTH));
    }


    public static String getDurationTime(long time) {
        time = time / 1000;
        int minu = (int) (time / 60);
        int second = (int) time - (minu * 60);
        return (minu < 10 ? ("0" + minu) : minu) + ":"
                + (second < 10 ? ("0" + second) : second);
    }

    public static String getDurationTimeForFavorite(long time) {
//        time = time / 1000;
//        int minu = (int) (time / 60);
//        int second = (int) time - (minu * 60);
//        return (minu < 10 ? ("0" + minu) : minu) + "'"
//                + (second < 10 ? ("0" + second) : second) + "\"";
        return getDurationTime(time);
    }

    public static String stringForTime(long timeMs) {
        StringBuilder formatBuilder = new StringBuilder();
        Formatter formatter = new Formatter(formatBuilder, Locale.getDefault());
        long totalSeconds = timeMs / 1000;

        long seconds = totalSeconds % 60;
        long minutes = (totalSeconds / 60) % 60;
        long hours = totalSeconds / 3600;
        formatBuilder.setLength(0);
        if (hours > 0) {
            return formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return formatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }

    public static String getTimeBetween(long start, long end) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(start);
        String startStr = format.format(calendar.getTime());

        calendar = Calendar.getInstance();
        calendar.setTimeInMillis(end);
        String endStr = format.format(calendar.getTime());

        String date = startStr.substring(0, 10);

        return date + startStr.replace(date, "") + "~" + endStr.replace(date, "");
    }

    public static String getUseTime(long timeSec) {
        StringBuilder formatBuilder = new StringBuilder();
        Formatter formatter = new Formatter(formatBuilder, Locale.getDefault());
        long totalSeconds = timeSec;

        long seconds = totalSeconds % 60;
        long minutes = (totalSeconds / 60) % 60;
        long hours = totalSeconds / 3600;
        formatBuilder.setLength(0);
        return formatter.format("%02d:%02d:%02d", hours, minutes, seconds).toString();
    }

    public static boolean isSameDay(long time1, long time2) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time1);
        String date1 = format.format(calendar.getTime());
        calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time2);
        String date2 = format.format(calendar.getTime());
        return date2.equals(date1);
    }

    /**
     * @param date: yyyy-MM-dd
     * @return
     */
    public static long dateToLong(String date) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            return format.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * HH:mm:ss
     *
     * @param time
     * @return
     */
    public static String dateToHHMMSS(long time) {
        if (time <= 0) {
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        String timeString = format.format(calendar.getTime());
        return timeString;
    }

    /**
     * yyyy-MM-dd HH:mm:ss
     *
     * @param time
     * @return
     */
    public static String dateToYYYYMMDDHHSS(long time) {
        if (time <= 0) {
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        String timeString = format.format(calendar.getTime());
        return timeString;
    }

    /**
     * yyyy-MM-dd HH:mm
     *
     * @param time
     * @return
     */
    public static String dateToYYYYMMDDHHMM(long time) {
        if (time <= 0) {
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        String timeString = format.format(calendar.getTime());
        return timeString;
    }

    public static String dateToYYYYMMDD(long time) {
        if (time <= 0) {
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        String timeString = format.format(calendar.getTime());
        return timeString;
    }

    public static String dateToMMDD(long time) {
        SimpleDateFormat format = new SimpleDateFormat("MM-dd");

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        String timeString = format.format(calendar.getTime());
        return timeString;
    }

    public static String dateToDD(long time) {
        SimpleDateFormat format = new SimpleDateFormat("dd");

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        String timeString = format.format(calendar.getTime());
        return timeString;
    }

    public static String dateToYYYY(long time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy");
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        String timeString = format.format(calendar.getTime());
        return timeString;
    }

    public static String dateToMM(long time) {
        SimpleDateFormat format = new SimpleDateFormat("MM");
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        String timeString = format.format(calendar.getTime());
        return timeString;
    }

    public static String dateToYYYYMM(long time) {
        String yyyymm = "";
        String mm = dateToMM(time);
        int mmInt = Integer.parseInt(mm);
        yyyymm = getMonthEnglish(mmInt) + " . " + dateToYYYY(time);
        return yyyymm;
    }

    private static String getMonthEnglish(int month) {
        String monthString = "";
        switch (month) {
            case 1:
                monthString = "Jan";
                break;
            case 2:
                monthString = "Feb";
                break;
            case 3:
                monthString = "Mar";
                break;
            case 4:
                monthString = "Apr";
                break;
            case 5:
                monthString = "May";
                break;
            case 6:
                monthString = "Jun";
                break;
            case 7:
                monthString = "Jul";
                break;
            case 8:
                monthString = "Agu";
                break;
            case 9:
                monthString = "Sep";
                break;
            case 10:
                monthString = "Oct";
                break;
            case 11:
                monthString = "Nov";
                break;
            case 12:
                monthString = "Dec";
                break;
        }
        return monthString;
    }

    public static String dateToChinaYYYYMM(long time, String year, String month) {
        String mm = dateToMM(time);
        return dateToYYYY(time) + year + mm + month;
    }

    /**
     * 将时间戳转为代表"距现在多久之前"的字符串
     *
     * @param timeStr 毫秒
     * @return
     */
    public static String getStandardDate(String timeStr) {
        try {
            return getStandardDate(Long.parseLong(timeStr));
        } catch (Exception e) {
            return "";
        }
    }

    public static String getStandardDate(long timestampMS) {
        try {
            long diffMS = System.currentTimeMillis() - timestampMS;
            Calendar oldCalendar = Calendar.getInstance();
            oldCalendar.setTimeInMillis(timestampMS);
            Calendar currentCalendar = Calendar.getInstance();
            int diffDay = currentCalendar.get(Calendar.DAY_OF_YEAR) - oldCalendar.get(Calendar.DAY_OF_YEAR);
            int diffYear = currentCalendar.get(Calendar.YEAR) - oldCalendar.get(Calendar.YEAR);
            if (diffMS < 0) {
                return "刚刚";
            }
            if (diffYear == 0) {
                if (diffDay < 0) {
                    return "刚刚";
                } else if (diffDay < 1) {
                    if (diffMS < 1 * 60 * 1000) {
                        return "刚刚";
                    } else if (diffMS < 60 * 60 * 1000) {
                        return diffMS / (60 * 1000) + " 分钟前";
                    } else {
                        return diffMS / (60 * 60 * 1000) + " 小时前";
                    }
                } else if (diffDay < 2) {
                    return "昨天 " + DateFormatUtil.formatMS("HH:mm", timestampMS);
                } else {
                    return DateFormatUtil.formatMS("MM-dd", timestampMS);
                }
            } else if (diffYear > 0) {
                return DateFormatUtil.formatMS("YYYY-MM-dd", timestampMS);
            } else {
                return "刚刚";
            }
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 格式化时间（输出类似于 刚刚, 4分钟前, 一小时前, 昨天这样的时间）
     *
     * @param time    需要格式化的时间 如"2014-07-14 19:01:45"
     * @param pattern 输入参数time的时间格式 如:"yyyy-MM-dd HH:mm:ss"
     *                <p/>
     *                如果为空则默认使用"yyyy-MM-dd HH:mm:ss"格式
     * @return time为null，或者时间格式不匹配，输出空字符""
     */
    public static String formatDisplayTime(String time, String pattern) {
        String display = "";
        int tMin = 60 * 1000;
        int tHour = 60 * tMin;
        int tDay = 24 * tHour;

        if (time != null) {
            if (pattern == null)
                pattern = "yyyy-MM-dd HH:mm:ss";
            try {
                Date tDate = new SimpleDateFormat(pattern).parse(time);
                Date today = new Date();
                SimpleDateFormat thisYearDf = new SimpleDateFormat("yyyy");
                SimpleDateFormat todayDf = new SimpleDateFormat("yyyy-MM-dd");
                Date thisYear = new Date(thisYearDf.parse(thisYearDf.format(today)).getTime());
                Date yesterday = new Date(todayDf.parse(todayDf.format(today)).getTime());
                Date beforeYes = new Date(yesterday.getTime() - tDay);
                if (tDate != null) {
                    @SuppressWarnings("unused")
                    SimpleDateFormat halfDf = new SimpleDateFormat("MM月dd日");
                    long dTime = today.getTime() - tDate.getTime();
                    if (tDate.before(thisYear)) {
                        display = new SimpleDateFormat("yyyy年MM月dd日").format(tDate);
                    } else {

                        if (dTime < tMin) {
                            display = "刚刚";
                        } else if (dTime < tHour) {
                            display = (int) Math.ceil(dTime / tMin) + "分钟前";
                        } else if (dTime < tDay && tDate.after(yesterday)) {
                            display = (int) Math.ceil(dTime / tHour) + "小时前";
                        } else if (tDate.after(beforeYes) && tDate.before(yesterday)) {
                            display = "昨天  " + new SimpleDateFormat("HH:mm").format(tDate);
                        } else {
                            display = multiSendTimeToStr(tDate.getTime() / 1000);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return display;
    }

    /**
     * 群发使用的时间转换
     */
    public static String multiSendTimeToStr(long timeStamp) {

        if (timeStamp == 0)
            return "";
        Calendar inputTime = Calendar.getInstance();
        String timeStr = timeStamp + "";
        if (timeStr.length() == 10) {
            timeStamp = timeStamp * 1000;
        }
        inputTime.setTimeInMillis(timeStamp);
        Date currenTimeZone = inputTime.getTime();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        if (calendar.before(inputTime)) {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            return sdf.format(currenTimeZone);
        }
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        if (calendar.before(inputTime)) {
            @SuppressWarnings("unused")
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            return "昨天";
        } else {
            calendar.add(Calendar.DAY_OF_MONTH, -5);
            if (calendar.before(inputTime)) {
                return getWeekDayStr(inputTime.get(Calendar.DAY_OF_WEEK));
            } else {
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                calendar.set(Calendar.MONTH, Calendar.JANUARY);
                if (calendar.before(inputTime)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("M" + "/" + "d" + " ");
                    String temp1 = sdf.format(currenTimeZone);
                    SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm");
                    String temp2 = sdf1.format(currenTimeZone);
                    return temp1 + temp2;
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy" + "/" + "M" + "/" + "d" + " ");
                    String temp1 = sdf.format(currenTimeZone);
                    SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm");
                    String temp2 = sdf1.format(currenTimeZone);
                    return temp1 + temp2;
                }
            }
        }
    }

    /**
     * 时间转化为星期
     *
     * @param indexOfWeek 星期的第几天
     */
    public static String getWeekDayStr(int indexOfWeek) {
        String weekDayStr = "";
        switch (indexOfWeek) {
            case 1:
                weekDayStr = "星期日";
                break;
            case 2:
                weekDayStr = "星期一";
                break;
            case 3:
                weekDayStr = "星期二";
                break;
            case 4:
                weekDayStr = "星期三";
                break;
            case 5:
                weekDayStr = "星期四";
                break;
            case 6:
                weekDayStr = "星期五";
                break;
            case 7:
                weekDayStr = "星期六";
                break;
        }
        return weekDayStr;
    }


    /**
     * 将时间转换为时间戳
     */
    public static long getStringDataToLong(String time) {
        if (TextUtils.isEmpty(time)) {
            return 0;
        }
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = simpleDateFormat.parse(time);
            long ts = date.getTime();
            return ts;
        } catch (Exception e) {

        }
        return 0;
    }

    public static String getClickCount(String value) {
        int count = Integer.valueOf(value).intValue();
        if (count > 1000000) {
            float temp = count * 1.0f / 10000 * 1.0f;
            BigDecimal mData = new BigDecimal(temp).setScale(0, BigDecimal.ROUND_HALF_UP);
            value = mData.toString() + "万";
        } else if (count > 10000) {
            float temp = count * 1.0f / 10000 * 1.0f;
            BigDecimal mData = new BigDecimal(temp).setScale(1, BigDecimal.ROUND_HALF_UP);
            value = mData.toString() + "万";
        }
        return value;
    }


    public static String generateTime(long position) {
        int totalSeconds = (int) (position / 1000);

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        if (hours > 0) {
            return String.format(Locale.US, "%02d:%02d:%02d", hours, minutes,
                    seconds).toString();
        } else {
            return String.format(Locale.US, "%02d:%02d", minutes, seconds)
                    .toString();
        }
    }


}
